const { request } = require('../../services/request')

// pages/edit-user.js
Page({
    /**
     * 页面的初始数据
     */
    data: {
        type: '', // edit new
        bmi: '',
        name: '',
        month: '',
        age: '',
        height: '',
        weight: '',
        answeUserPhone: '',
        answeUserName: '',
        sex: '',
        relation: '',
        relationList: ['本人', '夫妻', '子女', '朋友', '其他'],
        showMonth: false,
        birthday: '',
        currentDate: '',
        showAge: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const today = new Date()
        const currentDate = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate()

        this.setData({
            type: options.type,
            id: options.id,
            currentDate
        })

        if (options.type === 'edit') {
            request("POST", `/applet/answer/user/get/${options.id}`).then(res => {
                const {
                    month,
                    age,
                    height,
                    weight,
                    answeUserPhone,
                    answeUserName,
                    sex,
                    relation,
                    userId,
                    birthDate
                } = res.data
                let showMonth = age == 0
                this.setData({
                    month,
                    age,
                    height,
                    weight,
                    answeUserPhone,
                    answeUserName,
                    sex,
                    relation,
                    userId,
                    showMonth,
                    birthday: birthDate ? birthDate.substring(0, 10) : ''
                })

                this.data.birthday && this.handleShowAge(this.data.birthday)
            })
        } else {
            // this.setData({ birthday: currentDate })
        }


    },
    handleInputBlur() {
        if (this.data.height && this.data.weight) {
            let height = +this.data.height
            let weight = +this.data.weight
            this.setData({
                bmi: Math.floor(weight / (Math.pow(height / 100, 2)))
            })
        }
    },
    handleSexChange(e) {
        this.setData({
            sex: e.detail.value
        })
    },
    handelInputChange(e) {
        console.log(e)
        let comp = e.currentTarget.id
        let value = e.detail.value
        switch (comp) {
            case 'relation':
                this.setData({
                    relation: value,
                })
                break
            case 'answeUserName':
                this.setData({
                    answeUserName: value,
                })
                break
            case 'answeUserPhone':
                this.setData({
                    answeUserPhone: value,
                })
                break
            case 'age':
                this.setData({
                    age: value,
                })
                if (value == 0) {
                    this.setData({
                        showMonth: true
                    })
                } else {
                    this.setData({
                        showMonth: false
                    })
                }

                break
            case 'month':
                this.setData({
                    month: value,
                })
                break
            case 'height':
                this.setData({
                    height: value,
                })
                break
            case 'weight':
                this.setData({
                    weight: value,
                })
                break
        }
        if (this.data.height && this.data.weight) {
            let height = +this.data.height
            let weight = +this.data.weight
            this.setData({
                bmi: Math.floor(weight / Math.pow(height / 100, 2)),
            })
        }
    },
    handleConfirm() {
        const { month, age, height, weight, answeUserPhone, answeUserName, sex, relation } = this.data
        let valid = this.validation()
        const { userId } = JSON.parse(wx.getStorageSync('userInfo'))
        const params = {
            month,
            age,
            height,
            weight,
            answeUserPhone,
            answeUserName,
            sex,
            relation,
            userId,
            birthDate: this.data.birthday

        }
        let url = '/applet/answer/user/add'
        if (this.data.type === 'edit') {
            params.answeUserId = this.data.id
            url = '/applet/answer/user/edit'
        }
        if (valid) {
            request('POST', url, params)
                .then((res) => {
                    wx.navigateBack({
                        url: '/pages/user-list/index',
                    })
                })
                .catch((e) => {
                    wx.showToast({
                        title: e.msg,
                        icon: 'error',
                    })
                })
        }
    },
    handelCancel() {
        wx.navigateBack({
            delta: 1,
            success: (res) => {},
            fail: (res) => {},
            complete: (res) => {},
        })
    },
    bindDateChange(e) {
        console.log('bindDateChange e :>> ', e);
        this.handleShowAge(e.detail.value)
    },
    handleShowAge(d) {
        let [year, months, day] = d.split('-')
        let currentYear = new Date().getFullYear()
        let currentMonth = new Date().getMonth() + 1
        let currentDate = new Date().getDate()
        if (currentYear - year != 0) {
            let a = currentYear - year
            this.setData({
                age: a,
                month: 0,
                showAge: a + ' 岁'
            })
            return
        } else {
            let m = Math.max(currentMonth - months, 1)
            this.setData({
                age: 0,
                month: m,
                showAge: m + ' 个月'
            })
        }
    },
    validation() {
        const {
            month,
            age,
            height,
            weight,
            answeUserPhone,
            answeUserName,
            sex,
            relation,
            birthday
        } = this.data
        var valid = true
            //昵称：匹配非中英文数字
        let regName = RegExp(/[^ \u4e00-\u9fff0-9a-zA-Z_]/)
        if (answeUserName === '' || regName.test(answeUserName)) {
            console.log('test name :>> ', answeUserName)
            wx.showToast({
                title: '请检查姓名',
                icon: 'error',
            })
            valid = false
            return valid
        }
        if (answeUserName.length > 5) {
            wx.showToast({
                title: '姓名应小于5字',
                icon: 'error',
            })
            valid = false
            return valid
        }
        //性别
        if (sex === '') {
            wx.showToast({
                title: '请检查性别',
                icon: 'error',
            })
            valid = false
            return valid
        }
        //手机号：匹配11位数字
        let regPhone = RegExp(/^\d{11}$/)
        if (answeUserPhone !== null && answeUserPhone !== '' && !regPhone.test(answeUserPhone)) {
            wx.showToast({
                title: '请检查手机号码',
                icon: 'error',
            })
            valid = false
            return valid
        }

        // 生日必填
        if (!birthday) {
            wx.showToast({
                title: '请选择生日',
                icon: 'error',
            })
            valid = false
            return valid
        }
        //年龄：月小于12
        // let regNum = RegExp(/[^ 0-9]+/)
        // if (!age || age === '0') {
        //     console.log('age,month :>> ', age, month);
        //     if (age === 0 || age === '0') {
        //         console.log('age===0 :>> ', age, month);
        //         if (!month || month == '') {

        //             wx.showToast({
        //                 title: '请输入月份',
        //                 icon: 'error',
        //             })
        //             valid = false
        //             return valid
        //         } else {
        //             if (month != '' && month > 12) {
        //                 wx.showToast({
        //                     title: '请检查年龄',
        //                     icon: 'error',
        //                 })
        //                 valid = false
        //                 return valid
        //             }
        //         }
        //     } else {
        //         wx.showToast({
        //             title: '请输入年龄',
        //             icon: 'error',
        //         })
        //         valid = false
        //         return valid
        //     }
        // }


        return valid
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})